package com.steam.splace;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import thread.DoThread;
import thread.DoThreadGet;

import bo.UserFunctions;

import com.google.android.gms.internal.ca;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;



import dao.DataAccess;
import entity.Category;
import entity.Message;
import entity.Region;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddPlaceActivity extends FragmentActivity implements
		LocationListener {
	ArrayAdapter<String> adapter;
	private final int addplace_tag = 7;
	private final int category_tag = 4;
	private final int getfavorite_tag = 9;
	private final int region_tag = 17;
	Spinner spCategory, spRegion;
	GoogleMap googleMap;
	int positionOnSpinCat = 0;
	int positionOnSpinReg = 0;
	ArrayList<String> dataCat;
	ArrayList<LatLng> markerPoints;
	Menu menu;
	float zoomlevel = 8;
	Location location;
	ArrayList<Integer> listCatID = new ArrayList<Integer>();;
	Activity currentActivity;
	int uid = -1;
	TextView longitude, latitude, placename, description, address;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addplace_activity);
		currentActivity = this;
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);
		longitude = (TextView) findViewById(R.id.txtLongitude);
		latitude = (TextView) findViewById(R.id.txtLatitude);
		placename = (TextView) findViewById(R.id.txtPlaceName);
		description = (TextView) findViewById(R.id.txtDescription);
		address = (TextView) findViewById(R.id.txtAddress);
		spCategory = (Spinner) findViewById(R.id.spCategory);
		spRegion = (Spinner) findViewById(R.id.spRegion);
		googleMap = fm.getMap();
		googleMap.setMyLocationEnabled(true);
		
		LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
		Criteria cr = new Criteria();
		String provider = locationmanager.getBestProvider(cr, true);
		location = locationmanager.getLastKnownLocation(provider);
		if (location != null) {
			onLocationChanged(location);
			locationmanager.requestLocationUpdates(provider, 20000, 0, this);
			location = locationmanager.getLastKnownLocation(provider);
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(
					new LatLng(lat, lng), zoomlevel);
			googleMap.animateCamera(cameraUpdate1);
			Log.v("my location", lat + "/" + lng);
		}
		// load category and region
		ArrayList<Category> cats = new ArrayList<Category>();
		Gson gson = new Gson();
		int catSize = prefs.getInt("categorysize", 0);
		ArrayList<Region> regions = new ArrayList<Region>();
		int regionSize = prefs.getInt("regionsize", 0);
		for (int i = 0; i < catSize; i++) {
			String json = prefs.getString("category_" + i, "");
			cats.add(gson.fromJson(json, Category.class));
		}
		for (int i = 0; i < regionSize; i++) {
			String json = prefs.getString("region_" + i, "");
			regions.add(gson.fromJson(json, Region.class));
		}
		loadCats(cats);
		loadRegion(regions);

		// Getting GoogleMap object from the fragment

		googleMap.setOnMapClickListener(new OnMapClickListener() {
			@Override
			public void onMapClick(LatLng point) {
				googleMap.clear();
				// TODO Auto-generated method stub
				longitude.setText(point.longitude + "");
				latitude.setText(point.latitude + "");
				Marker marker = googleMap.addMarker(new MarkerOptions()
						.position(new LatLng(point.latitude, point.longitude)));
				CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
						new LatLng(point.latitude, point.longitude), 14);
				googleMap.animateCamera(cameraUpdate);
			}
		});
	}

	public void loadCats(ArrayList<Category> cat) {
		if (cat != null) {
			ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this,
					android.R.layout.simple_spinner_item, cat);
			adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
			Spinner spCategory = (Spinner) this.findViewById(R.id.spCategory);
			spCategory.setAdapter(adapter);
		}
	}

	public void loadRegion(ArrayList<Region> region) {
		if (region != null) {
			ArrayAdapter<Region> adapter = new ArrayAdapter<Region>(this,
					android.R.layout.simple_spinner_item, region);
			adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
			Spinner spRegion = (Spinner) this.findViewById(R.id.spRegion);
			spRegion.setAdapter(adapter);
		}
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btAddMoreCat) {
			TextView allCat = (TextView) this.findViewById(R.id.txtAllCat);
			boolean exist = false;
			for (int i = 0; i < listCatID.size(); i++) {
				if (listCatID.get(i) == ((Category) (spCategory
						.getSelectedItem())).getCategoryid()) {
					exist = true;
					break;
				}
			}
			if (exist == false) {
				if (allCat.getText().toString().equals("")) {
					allCat.setText(((Category) (spCategory.getSelectedItem()))
							.getCategoryName());
					listCatID.add(((Category) (spCategory.getSelectedItem()))
							.getCategoryid());
				} else {
					allCat.setText(allCat.getText()
							+ ";"
							+ ((Category) (spCategory.getSelectedItem()))
									.getCategoryName());
					listCatID.add(((Category) (spCategory.getSelectedItem()))
							.getCategoryid());
				}
			}
		} else if (id == R.id.btAdd) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("placename", (placename.getText()
					.toString())));
			params.add(new BasicNameValuePair("description", description
					.getText().toString()));
			params.add(new BasicNameValuePair("address", address.getText()
					.toString()));
			params.add(new BasicNameValuePair("longitude", longitude.getText()
					.toString()));
			params.add(new BasicNameValuePair("latitude", latitude.getText()
					.toString()));
			params.add(new BasicNameValuePair("regionid", ((Region) (spRegion
					.getSelectedItem())).getId() + ""));
			Log.v("regid", ((Region) (spRegion
					.getSelectedItem())).getId() + "");
			for (int i = 0; i < listCatID.size(); i++) {
				params.add(new BasicNameValuePair("categoryid" + i, listCatID
						.get(i) + ""));
				Log.v("catid", listCatID.get(i) + "");
			}
			for (int i = 0; i < params.size(); i++) {
				System.out.println(params.get(i).getName() + "/"
						+ params.get(i).getValue());

			}
			listCatID = new ArrayList<Integer>();
			ArrayList l = new ArrayList();
			l.add(addplace_tag);
			l.add(params);
			DoThread thread = new DoThread(this);
			thread.execute(l);
		}
	}

	private void fillCategory() {

		spRegion.setOnItemSelectedListener(new MyEventReg());
		spCategory.setOnItemSelectedListener(new MyEvent());
	}

	private class MyEventReg implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			positionOnSpinReg = arg2;
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	private class MyEvent implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			positionOnSpinCat = arg2;
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	public int getUID() {

		DoThreadGet thread1 = new DoThreadGet(this);
		ArrayList params1 = new ArrayList();
		params1.add(getfavorite_tag);
		DataAccess da = new DataAccess(this);
		int uid = -1;
		try {
			da.open();
			if (da.getUserInUse() != null)
				uid = da.getUserInUse().getId();
			else
				uid = -1;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			uid = -1;
		} finally {
			da.close();
		}
		return uid;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.main, menu);

		this.menu = menu;
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		if (uid != -1) {
			getMenuInflater().inflate(R.menu.main, menu);
		} else
			getMenuInflater().inflate(R.menu.menunologin, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.menuSearch) {
			if (!this.getClass().getSimpleName().equals("SearchActivity")) {

				Intent searchIntent = new Intent(this, SearchActivity.class);
				startActivity(searchIntent);
			}
		} else if (item.getItemId() == R.id.menuProfile) {
			if (!this.getClass().getSimpleName().equals("ProfileActivity")) {
				Intent profileIntent = new Intent(this, ProfileActivity.class);
				startActivity(profileIntent);
			}
		} else if (item.getItemId() == R.id.SignOut) {
			DataAccess da = new DataAccess(this);
			try {
				da.open();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			da.signOut();
			da.close();
			this.finish();
			Intent loginIntent = new Intent(this, MainActivity.class);
			startActivity(loginIntent);
		} else if (item.getItemId() == R.id.menuSignUp) {
			if (!this.getClass().getSimpleName().equals("SignUpActivity")) {

				Intent signUpActivity = new Intent(this, SignUpActivity.class);
				startActivity(signUpActivity);
			}
		} else if (item.getItemId() == R.id.menuForgot) {
			if (!this.getClass().getSimpleName()
					.equals("ForgotPasswordActivity")) {
				Intent forgotPasswordActivity = new Intent(this,
						ForgotPasswordActivity.class);
				startActivity(forgotPasswordActivity);
			}
		} else if (item.getItemId() == R.id.menuAddPlace) {
			if (!this.getClass().getSimpleName().equals("AddPlaceActivity")) {
				Intent addPlaceActivity = new Intent(this,
						AddPlaceActivity.class);
				startActivity(addPlaceActivity);
			}
		} else if (item.getItemId() == R.id.menuSignIn) {
			if (!this.getClass().getSimpleName().equals("MainActivity")) {
				Intent mainActivity = new Intent(this, MainActivity.class);
				startActivity(mainActivity);
			}
		} else if (item.getItemId() == R.id.menuSearchArea) {
			if (!this.getClass().getSimpleName().equals("SearchByAreaActivity")) {
				Intent mainActivity = new Intent(this,
						SearchByAreaActivity.class);
				startActivity(mainActivity);
			}
		}		else if(item.getItemId() == R.id.menuFavorite){
			if (!this.getClass().getSimpleName().equals("FavoriteActivity")) {

				Intent favoriteActivity = new Intent(this, FavoriteActivity.class);
				startActivity(favoriteActivity);
			}
		}
		
		return true;
	}
}
